const { User } = require('../models')
const jwt = require('jsonwebtoken')
const config = require('../config/config')

function jwtSignUser (user) {
  const ONE_WEEK = 60 * 60 * 24 * 7
  return jwt.sign(user, config.authentication.jwtSecret, {
    expiresIn: ONE_WEEK
  })
}

module.exports = {
  async register (req, res) {
    try {
      const user = await User.create(req.body)
      const userJson = user.toJSON()
      res.send({
        user: userJson,
        token: jwtSignUser(userJson)
      })
    } catch (err) {
      res.status(400).send({
        error: 'This email account is already in use.'
      })
    }
  },

  async AdminLogin (req, res) {
    try {
      var admin = {
        account: 'admin',
        password: 'abc.123'
      }
      if (req.body.account === admin.account && req.body.password === admin.password) {
        res.send({
          token: jwtSignUser(admin)
        })
      } else {
        res.status(400).send({
          error: '用户名或密码错误！'
        })
      }
    } catch (err) {
      res.status(400).send({
        error: '后台登录错误！'
      })
    }
  }
}
